package com.sm.activity.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sm.activity.feigns.TicketFeignClient;
import com.sm.activity.mapper.ActivityOperMapper;
import com.sm.activity.mapper.ActivityTicketOperMapper;
import com.sm.tool.entity.dto.ActivityDetails;
import com.sm.tool.entity.dto.SentTicketDTO;
import com.sm.tool.entity.dto.SentTicketsDTO;
import com.sm.tool.entity.po.Activity;
import com.sm.tool.entity.po.ActivityTicket_;
import com.sm.tool.entity.po.Tickets_;
import com.sm.tool.entity.po.User_;
import com.sm.tool.entity.request.ActivityBingTicketRequest;
import com.sm.tool.entity.request.AddActivityRequest;
import com.sm.tool.entity.request.PageInfo;
import com.sm.tool.entity.request.ParticipateaActivityRequest;
import com.sm.tool.entity.response.ReturnData;
import com.sm.tool.entity.vo.ActivityTicketsDetails;
import com.sm.tool.enums.NumberEnums;
import com.sm.tool.enums.ResultEnums;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisCluster;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ActivityOperService {


    @Autowired
    private ActivityOperMapper activityOperMapper;

    @Autowired
    private ActivityTicketOperMapper activityTicketOperMapper;

    @Autowired
    private TicketFeignClient ticketFeignClient;

    @Autowired
    private JedisCluster jedisCluster;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public ReturnData addActivity(AddActivityRequest addActivityRequest) {
        Activity activity = Activity.builder().build();
        BeanUtils.copyProperties(addActivityRequest, activity);
        /**
         * 创建活动
         */
        activityOperMapper.insert(activity);
        Long activityId = activity.getId();

        /**
         * 设置该活动绑定的券
         */
        List<ActivityBingTicketRequest> activityBingTicketRequestList = addActivityRequest.getActivityBingTicketRequestList();

        for (ActivityBingTicketRequest activityBingTicketRequest : activityBingTicketRequestList) {

            activityTicketOperMapper.insert(
                    ActivityTicket_.builder()
                            .activityId(activityId)
                            .ticketId(activityBingTicketRequest.getTicketId())
                            .number(activityBingTicketRequest.getNum())
                            .version(Long.parseLong(String.valueOf(NumberEnums.ONE.getNumber())))
                            .build()
            );
        }

        return ReturnData.builder().build();
    }

    public ReturnData queryActivitys(PageInfo pageInfo) {
        List<ActivityDetails> activityDetails = activityOperMapper.queryActivityDetails();

        List<Long> ticketIds = new ArrayList<>();
        log.info(activityDetails.size() + "");
        for (ActivityDetails details : activityDetails) {
            List<ActivityTicketsDetails> activityTicketsDetails = details.getActivityTicketsDetails();
            for (ActivityTicketsDetails activityTicketsDetails1 : activityTicketsDetails) {
                ticketIds.add(activityTicketsDetails1.getId());
            }
        }
        Long[] ticketIdArray = new Long[ticketIds.size()];
        ticketIds.toArray(ticketIdArray);
        List<Tickets_> ticketsList = ticketFeignClient.queryTicketListByIds(ticketIdArray);

        for (ActivityDetails details : activityDetails) {
            List<ActivityTicketsDetails> activityTicketsDetails = details.getActivityTicketsDetails();
            for (ActivityTicketsDetails activityTicketsDetails1 : activityTicketsDetails) {
                for (Tickets_ tickets_ : ticketsList) {
                    if (tickets_.getId().equals(activityTicketsDetails1.getId())) {
                        BeanUtils.copyProperties(tickets_, activityTicketsDetails1);
                    }
                }
            }
        }

        return ReturnData.builder().Data(activityDetails).build();
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnData participateaActivity(String token, ParticipateaActivityRequest participateaActivityRequest) {


        String userIdStr = jedisCluster.get(token);
        if (userIdStr == null) {
            return ReturnData.builder().code(ResultEnums.ACCOUNT_EXPIRED.getCode()).build();
        }

        Long userId = Long.parseLong(userIdStr);

        Long activityId = participateaActivityRequest.getActivityId();
        Long ticketId = participateaActivityRequest.getTicketId();

        Activity activity = activityOperMapper.selectById(activityId);

        /**
         * 检查用户是否重复参加
         */
//        if (jedisCluster.hget(String.valueOf(ticketId), userIdStr) != null) {
//            return ReturnData
//                    .builder()
//                    .code(ResultEnums.only_be_attended_once.getCode())
//                    .Data(ResultEnums.only_be_attended_once.getMessage())
//                    .build();
//        }

        /**
         * 检查活动 是否正常
         * 过期
         * 是否上架
         */
        Long startTime = activity.getStartTime().getTime();
        Long endTime = activity.getEndTime().getTime();
        Long nowTime = System.currentTimeMillis();

        if (nowTime < startTime || nowTime > endTime) {
            return ReturnData.builder()
                    .msg(ResultEnums.ACTIVITYNOTSTART.getMessage())
                    .code(ResultEnums.ACTIVITYNOTSTART.getCode())
                    .build();
        }

        if (activity.getStatus() == NumberEnums.ZERO.getNumber()) {
            return ReturnData.builder()
                    .msg(ResultEnums.ACTIVITYNOTSTART.getMessage())
                    .code(ResultEnums.ACTIVITYNOTSTART.getCode())
                    .build();
        }

        /**
         * 检查该券 是否在该活动下
         */
        QueryWrapper<ActivityTicket_> activityTicketQueryWrapper = new QueryWrapper<>();
        activityTicketQueryWrapper.eq("activity_id", activityId)
                .eq("ticket_id", ticketId);
        ActivityTicket_ activityTicket_ = activityTicketOperMapper.selectOne(activityTicketQueryWrapper);

        if (activityTicket_.getNumber() <= 0) {
            return ReturnData.builder()
                    .msg(ResultEnums.Ticket_not_no.getMessage())
                    .code(ResultEnums.Ticket_not_no.getCode())
                    .build();
        }

        if (activityTicket_ == null) {
            return ReturnData.builder()
                    .msg(ResultEnums.RESOURCE_NOT_FOUND.getMessage())
                    .code(ResultEnums.RESOURCE_NOT_FOUND.getCode())
                    .build();
        }

        Long[] ticketArray = {ticketId};
        /**
         * 查询优惠券
         */
        List<Tickets_> tickets_s = ticketFeignClient.queryTicketListByIds(ticketArray);
        /**
         * 为用户分配卷
         */
        SentTicketDTO sentTicketDTO = SentTicketDTO.builder()
                .number(NumberEnums.ONE.getNumber())
                .tickets_(tickets_s.get(0))
                .build();

        List<SentTicketDTO> sentTicketDTOList = new ArrayList<>();
        sentTicketDTOList.add(sentTicketDTO);

        SentTicketsDTO sentTickestDTO =
                SentTicketsDTO.builder()
                        .sentTicketDTOList(sentTicketDTOList)
                        .userId(userId)
                        .build();


        /**
         * 活动卷 -1
         */
        UpdateWrapper<ActivityTicket_> activityTicketUpdateWrapper = new UpdateWrapper<>();
        activityTicketUpdateWrapper.eq("activity_id", activityId)
                .eq("ticket_id", ticketId);

        Integer number = activityTicket_.getNumber() - NumberEnums.ONE.getNumber();


        if (number <= NumberEnums.ZERO.getNumber()){
            return ReturnData.builder()
                    .msg(ResultEnums.Ticket_not_no.getMessage())
                    .code(ResultEnums.Ticket_not_no.getCode())
                    .build();
        }

        int sign = activityTicketOperMapper
                .updateById(
                        ActivityTicket_.builder().id(activityTicket_.getId())
                                .number(number)
                                .version(activityTicket_.getVersion())
                                .build()
                );
//        if (sign == 0) {
//            return ReturnData.builder()
//                    .msg(ResultEnums.Ticket_not_no.getMessage())
//                    .code(ResultEnums.Ticket_not_no.getCode())
//                    .build();
//        }
        /**
         * 发送到mq
         */
        rocketMQTemplate.syncSend("sm_sent_ticket_topic", sentTickestDTO);


        jedisCluster.hset(String.valueOf(ticketId), userIdStr, "");

        return ReturnData.builder().build();
    }
}
